<template>
	<view class="food_h" :style="{paddingTop: paddingHeight + 'px'}">
		<nav-bar></nav-bar>
		<view class="t-h-container">
			<view class="t-h-title">
				{{ type == 'add' ? '食物' : '编辑食物记录' }}
			</view>
			<view class="food_f">
				<view class="f_container">
					<view class="cell">
						<u-input placeholder="请输入食物名称" color="#545DDE" shape="square" border="none" inputAlign="right"
							v-model="foodInfo.foodName">
							<template slot="prefix" class="prefix">
								食物名称
							</template>
						</u-input>
					</view>
					<view class="cell">
						<u-input shape="square" border="none" readonly inputAlign="right">
							<template slot="prefix" class="prefix">
								<text>图片</text>
							</template>
							<!-- errorIcon="http://oss.antaimedical.com/images/static/2024/06/66764618eb14d0f049f44d23Eu32Tf8eWcBr6c96b6c1ce3f450bfbca58104d6a8b2b.png" -->
							<u-image slot="suffix" :showMenuByLongpress="false" width="40rpx" height="40rpx"
								@click="chooseImage"
								:src="foodInfo.picUrl ? foodInfo.picUrl : 'http://oss.antaimedical.com/images/static/2024/06/66764618eb14d0f049f44d23Eu32Tf8eWcBr6c96b6c1ce3f450bfbca58104d6a8b2b.png'"
								:lazy-load="true">
							</u-image>

						</u-input>
					</view>
					<view class="cell">
						<u-input placeholder="请填写数值" type="digit" color="#545DDE" placeholderClass="placeholderClass"
							shape="square" border="none" inputAlign="right" v-model="foodInfo.heat">
							<template slot="prefix" class="prefix">
								热量
							</template>
							<template slot="suffix" class="suffix ol">
								千卡
							</template>
						</u-input>
					</view>
					<view class="cell">
						<u-input placeholder="请填写数值" type="digit" color="#545DDE" placeholderClass="placeholderClass"
							shape="square" border="none" inputAlign="right" v-model="foodInfo.carbohydrate">
							<template slot="prefix" class="prefix">
								碳水化合物
							</template>
							<template slot="suffix" class="suffix">
								克
							</template>
						</u-input>
					</view>
					<view class="cell">
						<u-input placeholder="请填写数值" type="digit" color="#545DDE" placeholderClass="placeholderClass"
							shape="square" border="none" inputAlign="right" v-model="foodInfo.protein">
							<template slot="prefix" class="prefix">
								蛋白质
							</template>
							<template slot="suffix" class="suffix">
								克
							</template>
						</u-input>
					</view>
					<view class="cell">
						<u-input placeholder="请填写数值" type="digit" color="#545DDE" placeholderClass="placeholderClass"
							shape="square" border="none" inputAlign="right" v-model="foodInfo.fat">
							<template slot="prefix" class="prefix">
								脂肪
							</template>
							<template slot="suffix" class="suffix">
								克
							</template>
						</u-input>
					</view>
				</view>
			</view>
		</view>
		<view class="large_button" v-if="type == 'add'" @click="$u.throttle(add, 1200)">
			完成
		</view>
		<view class="handle_c" v-else>
			<view class="delete_btn" @click="$u.throttle(del, 1500)">
				删除
			</view>
			<view class="save_btn" @click="$u.throttle(update, 1500)">
				保存
			</view>
		</view>
	</view>
</template>

<script>
	import {
		findDietaryDetails,
		delDietaryRecord,
		updateDietaryRecord,
		addDietaryOneRecord
	} from '@/api/index.js'
	const dayjs = require('@/utils/dayjs.min.js');

	export default {
		data() {
			return {
				paddingHeight: uni.getStorageSync('navbarHeight'),
				userId: uni.getStorageSync("userId"),
				foodId: undefined,
				type: undefined,
				params: undefined,
				foodInfo: {
					dietaryTime: '',
					foodName: '',
					type: '',
					userId: '',
					carbohydrate: '',
					fat: '',
					heat: '',
					picUrl: '',
					protein: '',
				}
			}
		},
		onLoad(OPTIONS) {
			this.type = OPTIONS.type
			if (this.type == 'update') {
				this.foodId = OPTIONS.id
				this.fetchData()
			} else {
				this.params = JSON.parse(OPTIONS.params)
			}
		},
		methods: {
			// 获取运动类型
			async fetchData() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					id: this.foodId
				}
				try {
					const res = await findDietaryDetails(params)
					if (res.code == 200) {
						this.foodInfo = res.data
					}
				} catch (e) {
					//TODO handle the exception
				}
				uni.hideLoading()
			},
			async add() {
				if (!this.foodInfo.foodName) {
					uni.showToast({
						title: '请填写食物名称',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					title: '加载中...'
				})
				let body = {
					...this.foodInfo,
					dietaryTime: this.params.dietaryTime,
					mealId: this.params.mealId,
					type: this.params.type,
					userId: this.userId
				}
				try {
					const res = await addDietaryOneRecord(body)
					if (res.code == 200) {
						uni.showToast({
							title: '添加成功'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				} catch (e) {
					//TODO handle the exception
				}
				uni.hideLoading()
			},
			// 选择图片上传
			chooseImage() {
				let that = this;
				getApp().globalData.isPriviewApi = true
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					sourceType: ['album', 'camera'],
					sizeType: ['compressed'],
					success(res) {
						console.log('res', res)
						const src = res.tempFiles[0].tempFilePath;
						that.upload(src)
					},
					fail(err) {
						console.log(err)
					}
				});
			},
			upload(src) {
				uni.showLoading({
					title: '上传中...'
				})
				uni.uploadFile({ // uploadStaticImg  uploadImages
					url: 'https://antaimedical.com:5000/devicewx-upload/api/v1/upload/AliyunOss/uploadStaticImg',
					header: {
						Authorization: `Bearer ${uni.getStorageSync('token')}`
					},
					filePath: src,
					name: 'file',
					success: async (res) => {
						let obj = JSON.parse(res.data);
						console.log('obj', obj)
						if (obj.code == 200) {
							uni.showToast({
								title: '上传完成'
							})
							this.foodInfo.picUrl = obj.data
						} else {
							uni.showToast({
								title: obj.code,
								icon: 'error',
								duration: 2000
							});
						}
					},
					fail(err) {
						console.log(err)
					},
					complete() {
						uni.hideLoading();
					}
				});
			},
			async update() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					id: this.foodId,
					foodName: this.foodInfo.foodName,
					carbohydrate: this.foodInfo.carbohydrate,
					fat: this.foodInfo.fat,
					heat: this.foodInfo.heat,
					picUrl: this.foodInfo.picUrl,
					protein: this.foodInfo.protein
				}
				try {
					const res = await updateDietaryRecord(params)
					if (res.code == 200) {
						uni.showToast({
							title: '修改成功'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				} catch (e) {
					//TODO handle the exception
				}
				uni.hideLoading()
			},
			async del() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					id: this.foodId
				}
				try {
					const res = await delDietaryRecord(params)
					if (res.code == 200) {
						uni.showToast({
							title: '删除成功'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				} catch (e) {
					//TODO handle the exception
				}
				uni.hideLoading()
			}
		}
	}
</script>


<style lang="scss">
	page {
		min-height: 100%;
	}
</style>
<style lang="scss" scoped>
	.food_h {

		.food_f {
			margin-top: 48rpx;
			width: 100%;


			.f_t {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.t_l {
					font-size: 28rpx;
					font-family: PingFangSC-Medium, PingFang SC;
				}

				.icon-a-shanchu2 {
					font-size: 44rpx;
					color: #FA5151;
					padding-left: 16rpx;
				}

				.add_f {
					height: 44rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 0 24rpx;
					border-radius: 22rpx;
					background-color: #545DDE;
					color: #fff;
					font-size: 24rpx;
					line-height: 44rpx;

					.iconfont {
						font-size: 20rpx;
						padding-right: 8rpx;
					}
				}
			}

			.other {
				justify-content: flex-start;
			}

			.f_container {
				width: 100%;
				margin-top: 32rpx;
				padding: 0 32rpx;
				background-color: #FAFAFA;
				border-radius: 16rpx;

				.cell {
					padding: 0 16rpx;
					border-bottom: 2rpx solid #fff;

					/deep/ .u-input {
						height: 110rpx;
					}

					/deep/ .input-placeholder {
						font-size: 28rpx !important;
						color: rgba(#545DDE, .5) !important;
					}

					.suffix,
					.prefix {
						display: flex;
						align-items: center;
						font-size: 32rpx;
						color: #666666;
					}

					.suffix {
						color: #545DDE;
						padding-left: 48rpx;
						font-family: PingFangSC-Medium, PingFang SC;
					}


					.ol {
						padding-left: 16rpx;
					}
				}
			}

		}

		.large_button {
			position: fixed;
			bottom: 76rpx;
			left: 50%;
			transform: translateX(-50%);
		}
	}
</style>